package com.troila.cloud.simplify.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.troila.cloud.simplify.model.STitle;
import com.troila.cloud.simplify.repository.STitleRepository;

@Service
@Transactional
public class STitleService {
	
	@Autowired
	private STitleRepository sTitleRepository;
	
	
	public STitle save(STitle sTitle) {
		if(StringUtils.isEmpty(sTitle.getId())) {
			sTitle.setGmtCreate(new Date());
		}
		sTitle.setGmtUpdate(new Date());
		return sTitleRepository.save(sTitle);
	}
	
	public STitle findById(int id) {
		return sTitleRepository.findById(id);
	}
	
	public Page<STitle> getTitleList(int page, int size,String mediaKey) {
		//按照ID排序
		List<Order> orders=new ArrayList<Order>();
		orders.add( new Order(Direction.DESC,"gmtUpdate"));
		//按状态查询
		Pageable pageable = new PageRequest(page, size,new Sort(orders));
		return sTitleRepository.findAllByMediaKey(pageable,mediaKey);
	}
	
	public Page<STitle> getTitleListByStatus(int page, int size,String mediaKey) {
		//按照ID排序
		List<Order> orders=new ArrayList<Order>();
		orders.add( new Order(Direction.DESC,"gmtUpdate"));
		//按状态查询
		Pageable pageable = new PageRequest(page, size,new Sort(orders));
		/*Specification<STitle> specification = new Specification<STitle>() {

			@Override
			public Predicate toPredicate(Root<STitle> root,
					CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate _key = criteriaBuilder.equal(root.get("tStatus").as(Integer.class), 0);
				return criteriaBuilder.and(_key);
			}
		};*/
		return sTitleRepository.findAllByTStatusAndMediaKey(pageable,0,mediaKey);
	}
	

}